package com.sen.uaa.granter;

import com.sen.common.auth.token.CaAuthenticationToken;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * 支持CA授权
 * @author esjiang
 */
public class CaGranter extends AbstractTokenGranter {

    private static final String grant_type = "ca" ;

    private static final String key_num = "keyNum" ;

    private final AuthenticationManager authenticationManager;

    public CaGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, grant_type);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        String keyNum = parameters.get(key_num);
        Authentication authenticationToken = new CaAuthenticationToken(keyNum);
        ((AbstractAuthenticationToken)authenticationToken).setDetails(parameters);
        authenticationToken = authenticationManager.authenticate(authenticationToken);
        if (authenticationToken == null || !authenticationToken.isAuthenticated()){
            throw new InvalidGrantException("Could not authenticate ca: " + keyNum);
        }
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, authenticationToken);
    }
}
